package com.starblink.android.guang.push

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.starblink.android.guang.MainActivity
import com.starblink.android.guang.R
import com.starblink.basic.log.SKLogger

/**
 * Firebase消息服务
 * 主要功能：当APP处于前台时，接收消息
 * @note Guang处于前台时，不显示推送消息，因此onMessageReceived()不需要处理
 */
class MyFirebaseMessagingService : FirebaseMessagingService() {

    /**
     * 收到消息时回调
     *
     * @param remoteMessage 消息对象
     */
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        SKLogger.e(TAG, "MyFirebaseMessagingService-onMessageReceived", FCMUtils.showLog)
        //  There are two types of messages data messages and notification messages.
        //  (1)Data messages are handled here in onMessageReceived whether the app is in the foreground or background.
        //  Data messages are the type traditionally used with GCM.
        //  (2)Notification messages are only received here in onMessageReceived when the app is in the foreground.
        //  When the app is in the background an automatically generated notification is displayed. When the user taps
        //  on the notification they are returned to the app. Messages containing both notification and data payloads
        //  are treated as notification messages. The Firebase console always sends notification messages.

//        // 数据载荷
//        if (remoteMessage.data.isNotEmpty()) {
//            SKLogger.e(TAG, "数据消息:data= ${remoteMessage.data}")
//        }
//
//        // 通知消息
//        remoteMessage.notification?.let {
//            SKLogger.e(TAG, "通知消息:title=${it.title}, body=${it.body}")
//            sendNotification(it)
//        }
    }

    override fun onDeletedMessages() {
        super.onDeletedMessages()
        SKLogger.e(TAG, "MyFirebaseMessagingService-onDeletedMessages", FCMUtils.showLog)
    }

    /**
     * Called if the FCM registration token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the
     * FCM registration token is initially generated so this is where you would retrieve the token.
     */
    override fun onNewToken(token: String) {
        SKLogger.e(TAG, "MyFirebaseMessagingService-onNewToken: $token", FCMUtils.showLog)
        // 如果用户长期不关闭APP，在此处同步Fcm Token
        FCMUtils.syncFcmToken()
    }

//    /**
//     * 创建并发送消息
//     */
//    private fun sendNotification(message: RemoteMessage.Notification) {
//        val intent = Intent(this, MainActivity::class.java)
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_SINGLE_TOP)
//        val pendingIntent = PendingIntent.getActivity(
//            this, 0 /* Request code */, intent,
//            PendingIntent.FLAG_IMMUTABLE
//        )
//
//        val channelId = getString(R.string.default_notification_channel_id)
////        val channelName = getString(R.string.default_notification_channel_name)
//        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
//        val notificationBuilder = NotificationCompat.Builder(this, channelId)
//            .setSmallIcon(R.drawable.ic_notification)
//            .setContentTitle(message.title)
//            .setContentText(message.body)
//            .setAutoCancel(true)
//            .setSound(defaultSoundUri)
//            .setContentIntent(pendingIntent)
//
//        val notificationManager =
//            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//
////        // Since android Oreo notification channel is needed.
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
////            val channel = NotificationChannel(channelId, channelName,
////                    NotificationManager.IMPORTANCE_DEFAULT)
////            notificationManager.createNotificationChannel(channel)
////        }
//
//        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
//    }

    companion object {
        private const val TAG = "dss"
    }
}
